package dal

import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

import java.sql.Connection
import javax.sql.DataSource
import org.apache.log4j.Logger

/**
 * Connection Class : to get connection from data source 
 */
class DBConnectionService{

   boolean transactional = false
   static Logger gLogger = Logger.getLogger(DBConnectionService.class);
   def grailsApplication
   DataSource dataSource

   private static Connection conn = null;

   def setting

   void afterPropertiesSet() {
     this.setting = grailsApplication.config.setting
   } 

   /**
    * to get the current dataSource
    * @return
    */
   def getDataSource(){

     if(dataSource==null){
       //dataSource = AH.application.mainContext.dataSource
       dataSource = AH.application.mainContext.dataSourceUnproxied // for grails >= 1.3
     }
     gLogger.info "dataSource : ${dataSource}" 
   }

  /**
   *  to get the db connection from DataSource.groovy
   *  @return
   */
   Connection getConnection(){
    gLogger.info "Comming into getConnection method of DBConnection"
    getDataSource()
    gLogger.info "dataSource : ${dataSource}"
    if(dataSource!=null){
      if(conn==null ){
        conn = dataSource.getConnection()
      }
    }
    /* No need to close the connection B'Coz it would be handle by data source */ 
    gLogger.info "Out from getConnection method of DBConnection"
    return conn
    
   }
}
